# -*- coding: utf-8  -*-

__author__ = 'rsj217'


import uuid
import string
import re
import hashlib
import os
import random
import time
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string, get_template
from trail import settings
from email import send_mail
from PIL import Image

ALPHABET = string.ascii_uppercase + string.ascii_lowercase + \
           string.digits + '-_'
ALPHABET_REVERSE = dict((c, i) for (i, c) in enumerate(ALPHABET))
BASE = len(ALPHABET)
SIGN_CHARACTER = '$'


def num_encode(n):
    if n < 0:
        return SIGN_CHARACTER + num_encode(-n)
    s = []
    while True:
        n, r = divmod(n, BASE)
        s.append(ALPHABET[r])
        if n == 0: break
    return ''.join(reversed(s))

def generate_username(identifier):
    """
    Generate a valid username from identifier, it can be an mail address
    or phone number
    """
    guid = uuid.uuid1()
    return num_encode(guid.int)

def detect_identifier_type(identifier):
    mobile_regex = re.compile('^1\d{10}$')
    if mobile_regex.match(identifier) is not None:
        return 'phone'
    email_regex = re.compile(
        '^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')
    if email_regex.match(identifier) is not None:
        return 'email'
    return 'unknown'

def generate_active_token(identifier):
    salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
    return hashlib.sha1(salt+identifier).hexdigest()

def send_token(host, to_email, active_token):

    from_email, to = settings.DEFAULT_FROM_EMAIL, to_email

    context = {
        'host': host,
        "active_token": active_token,
        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
    }

    subject = render_to_string('email/active-subject.txt', context).encode('utf-8')
    text_content = render_to_string('email/active-text.txt', context).encode('utf-8')
    html_content = render_to_string('email/active-html.html', context).encode('utf-8')

    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

def send_active_token_async(host, to_email, active_token):

    from_email, to = settings.DEFAULT_FROM_EMAIL, to_email

    context = {
        'host': host,
        "active_token": active_token,
        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
    }

    subject = render_to_string('email/active-subject.txt', context).encode('utf-8')
    text_content = render_to_string('email/active-text.txt', context).encode('utf-8')
    html_content = render_to_string('email/active-html.html', context).encode('utf-8')

    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

    send_mail(subject, text_content, from_email)



def genfilename():
    random_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    return random_str

def allowed_file(file, allowed_extensions):
    return '.' in file and file.split('.', 1)[1] in allowed_extensions


def make_thumb(im, dirname, filename, extend, size=150):

    """
    >>> filepath = 'avatar/2014-11-06/pic.jpg'
    >>> new_dir_name = 'media/uploads/50'
    """
    new_dirname = os.path.join(settings.MEDIA_ROOT, str(size), dirname)
    if not os.path.exists(new_dirname):
        os.makedirs(new_dirname)
    new_file = os.path.join(new_dirname,
                            '{}.{}'.format(filename, extend))
    try:
        im.thumbnail((size, size))
        im.save(new_file)
    except:
        raise

def upload_image(filepath, extend='png'):
    """
    >>> filepath = 'avatar/2014-11-06/pic.jpg'
    >>> upload_file = 'media/uploads/avatar/2014-11-06/pic.jpg'
    >>> dirname = 'avatar/2014-11-06/'
    >>> file = 'pic.jpg'
    """
    upload_file = os.path.join(settings.MEDIA_ROOT, filepath)

    dirname, file = os.path.split(filepath)

    if allowed_file(file, settings.ALLOWED_EXTENSIONS):
        filename = genfilename()
        new_filepath = os.path.join(dirname, "{}.{}".format(filename, extend))
        im = Image.open(upload_file)
        make_thumb(im, dirname, filename, extend, 150)
        make_thumb(im, dirname, filename, extend, 50)
        im.close()
        return {'message': u'上传成功', 'success': True, 'new_filepath': new_filepath}
    else:
        return {'message': u'上传的图片格式不合法', 'success': False}

